﻿using CaptchaGen;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ZSZ.Common;
using ZSZ.CommonMvc;
using ZSZ.Iservice;

namespace ZSZ.AdminWeb.Controllers
{
    public class MainController : Controller
    {
        public IAdminUserService AdminUserService { get; set; }
        // GET: Main
        public ActionResult Index()
        {
            if (Session["adminUserId"] == null)
            {
                return Redirect("/Main/Login");
            }
            return View();
        }
        [HttpGet]
        public ActionResult Login()
        {
            if (Session["adminUserId"]!=null)
            {
                return Redirect("/Main/Index");
            }
            return View();
        }
        [HttpPost]
        public ActionResult Login(string name,string pass,string yan) {
            if (string.IsNullOrEmpty(name.Trim())&& string.IsNullOrEmpty(pass.Trim())&& string.IsNullOrEmpty(yan.Trim()))
            {
                return Json(new JsonCommon { Status="err",ErrorMsg="不能为空"});
            }
            if (yan!=(string)TempData["yan"])
            {
                return Json(new JsonCommon { Status = "err", ErrorMsg = "验证码错误" });
            }
            if (!AdminUserService.CheckLogin(name,pass))
            {
                return Json(new JsonCommon { Status = "err", ErrorMsg = "用户名或者密码错误" });
            }
            var admin = AdminUserService.GetByPhone(name);
            Session["adminUserId"] = admin.Id;
            Session["cityId"] = admin.CityID;
            return Json(new JsonCommon { Status="ok"});
        }
        public ActionResult Yan()
        {
            string code = CommonHelper.GenerateCaptchaCode(4);
            System.IO.MemoryStream ms = ImageFactory.GenerateImage(code, 60, 100, 20, 6);
            TempData["yan"] = code;
            return File(ms, "image/jpeg");
        }
    }
}